<template>
 <!--用户添加对话框-->
 <el-dialog 
  title="添加用户"
  v-model="addVisible"
  width="50%"  
  center
  @close="closeadd"
 >
 <el-form
    ref="ruleFormRef"
    :model="adduserForm"
    :rules="rules"
  >
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="adduserForm.userName" />
    </el-form-item>
    <el-form-item label="密码" prop="userPwd">
      <el-input v-model="adduserForm.userPwd" />
    </el-form-item>
    <el-form-item label="邮箱" prop="userMail">
      <el-input v-model="adduserForm.userMail" />
    </el-form-item>
    </el-form>
 <template #footer>
    <span class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="adduser">确定</el-button>
    </span>
 </template>
 </el-dialog>
    </template>

<script setup>
import { useUsersStore } from "../store/user"
import { storeToRefs } from "pinia"
import { reactive, toRefs, ref } from "vue"
import axios from "axios";
let store = useUsersStore()
let { addVisible } = storeToRefs(store)
let ress = reactive({
    adduserForm: {
        userName: '',
        userPwd: '',
        userMail: ''
    }
})
let { adduserForm } = toRefs(ress)
//自定义邮箱规则
var checkEmail = (rule, value, callback) => {
    let reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    if (reg.test(value)) {
        return callback()
    } else {
        callback(new Error("请输入合法邮箱"))
    }
}
let rules = reactive({
    userName: [
        { required: true, message: "请填写用户名", trigger: 'blur' },
        { min: 3, max: 10, message: "字符长度在3-10", trigger: 'blur' }
    ],
    userPwd: [
        { required: true, message: "请填写密码", trigger: 'blur' },
        { min: 6, max: 15, message: "字符长度在6-15", trigger: 'blur' }
    ],
    userMail: [
        { required: true, message: '请填写邮箱', trigger: 'blur' },
        { validator: checkEmail, trigger: 'blur' }
    ]
})
let ruleFormRef = ref()
//关闭对话框
function closeadd() {
    ruleFormRef.value.resetFields()
}
//点击确定
function adduser() {
    ruleFormRef.value.validate((bool) => {
        if (!bool) return
        axios.post("/users/add", ress.adduserForm).then((res) => {
            store.userloadData()
            store.addVisible = false
        })
    })
}
</script>

<style>

</style>